<?php


namespace app\admin\controller;


use app\admin\model\Admin;
use app\common\controller\admin\Base;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


class Category extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Category;
    }


    /**
     * 查看所有分类（不分页）
     */
    public function index()
    {
        //设置设置请求类型
        if ($this->request->isPost()) {
            $name = $this->request->post('name', '');
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $status = $this->request->post('status', '');
            $field = [
                'id',
                'pid',
                'name',
                'nickname',
                'create_time',
                'update_time',
                'weigh',
                'status',
                'admin_id'
            ];
            $where = [
                'is_del' => 0
            ];
            if ($status !== '') {
                $where['status'] = $status;
            }
            //取出所有分类
            $allList = $this->model
                ->field($field)
                ->where($where)
                ->order($sort, $order)
                ->select()
                ->toArray();
            $ret = $this->formatCategoryList($name, $allList);

            $this->success('列表', '', $ret);
        }
    }

    /**
     * 格式化分类数组
     * @param $name
     * @param $allList
     * @return array
     */
    public function formatCategoryList($name, $allList)
    {

        $allList = array_column($allList, null, 'id');
        if ($name != '') {
            $retList = search_array_by_key($allList, 'name', $name);
            $retList = array_column($retList, null, 'id');
        } else {
            $retList = $allList;
        }
        //组装数组
        $data = [];
        foreach ($retList as $key => $val) {
            //判断输出结果为父类
            if ($val['pid'] == 0) {
                if (empty($data[$val['id']])) {
                    $data[$val['id']] = $val;
                    $data[$val['id']]['son_list'] = [];
                } else {
                    $val['son_list'] = $data[$val['id']]['son_list'];
                    $data[$val['id']] = $val;
                }
            } else {
                //如果为子类处理逻辑
                if (empty($data[$val['pid']])) {
                    $data[$val['pid']]['son_list'] = [];
                }
                $data[$val['pid']]['son_list'][] = $val;
            }
        }

        //输出最终数组
        $retData = [];
        foreach ($data as $key => $value) {
            if (empty($value['name'])) {
                $son_list = $value['son_list'];
                $value = $allList[$key];
                $value['son_list'] = $son_list;
            }
            if (empty($value['son_list'])) {
                foreach ($allList as $v) {
                    if ($v['pid'] == $value['id']) {
                        $value['son_list'][] = $v;
                    }
                }
            }
            $retData[] = $value;
        }
        return $retData;
    }

    /**
     * 删除分类（软删  删除父类id  则子类同样删除）
     */
    public function delCategory()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.delete';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $row = $this->model->get($params['ids']);
                    if (!$row) {
                        $this->error('不存在的数据');
                    }
                    $delData = [
                        'is_del' => 1,
                        'admin_id' => $this->admin['id']
                    ];
                    $result = $row->allowField(true)->save($delData);

                    //删除子类
                    $this->model->allowField(true)->where(['pid' => $params['ids']])->update($delData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 单独获取分类列表
     * @param $pid
     */
    public function getCategoryAll($pid = 0)
    {
        $fields = [
            'id',
            'name',
            'nickname'
        ];
        $where = [
            'is_del' => 0,
            'status' => 1,
            'pid' => $pid
        ];
        $list = $this->model
            ->field(implode(',', $fields))
            ->where($where)
            ->select();
        $this->success('列表', '', ['list' => $list]);
    }
}